package com.huishu.tcm.config;

import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SaTokenException;
import com.huishu.tcm.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    public ResultVo exceptionHandler(Exception e){
        e.printStackTrace();
        ResultVo resultVo = new ResultVo();
        if(e instanceof com.huishu.tcm.util.exception.TcmException){
            resultVo.setCode(((com.huishu.tcm.util.exception.TcmException) e).getCode());
            resultVo.setMessage(e.getMessage());
            return resultVo;
        }else if(e instanceof NotRoleException){
            resultVo.setCode(com.huishu.tcm.util.exception.TcmExceptionEnum.USER_ACCOUN_NO_AUTHORITY.getCode());
            resultVo.setMessage(com.huishu.tcm.util.exception.TcmExceptionEnum.USER_ACCOUN_NO_AUTHORITY.getMsg());
            return resultVo;
        }else if(e instanceof SaTokenException){
            resultVo.setCode(com.huishu.tcm.util.exception.TcmExceptionEnum.USER_NOT_LOGIN.getCode());
            resultVo.setMessage(e.getMessage());
            return resultVo;
        }else if(e instanceof MethodArgumentNotValidException){
            resultVo.setCode(com.huishu.tcm.util.exception.TcmExceptionEnum.DATA_FIELD_VALUE_IS_INCORRECT.getCode());
            resultVo.setMessage(((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage());
            return resultVo;
        }else if(e instanceof DuplicateKeyException){
            resultVo.setCode(com.huishu.tcm.util.exception.TcmExceptionEnum.DATA_ALREADY_EXISTS.getCode());
            resultVo.setMessage(com.huishu.tcm.util.exception.TcmExceptionEnum.DATA_ALREADY_EXISTS.getMsg());
            return resultVo;
        }
        resultVo.setCode(500);
        resultVo.setMessage(e.getMessage());
        return resultVo;
    }
}
